package com.edu.compile.template;

import com.edu.compile.ParserHolder;
import com.edu.compile.TemplateModel;
import com.edu.compile.template.buffer.Buffer;
import com.edu.model.dto.NodeMetadata;
import com.edu.model.tree.v2.ConvertTree;
import com.edu.model.tree.v2.TreeNode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 编译后的模版存储结果
 *
 * @author yanzhao
 * @date 2021/10/22 12:00
 * @since 1.0.0
 */
public class TemplatePolymerization implements TemplateModel {

    public TemplatePolymerization() {
    }

    protected Buffer buffer = new Buffer();

    private List<NodeTemplateParse> templateModelList = new ArrayList<>();

    private ConvertTree<NodeTemplateParse> convertTree = new ConvertTree<>();

    public void addTemplate(NodeTemplateParse templateModel) {
        templateModelList.add(templateModel);
    }

    private String eventId;

    /**
     * 函数入口
     */
    private NodeMetadata requestEntry;

    private Set<String> requires = new HashSet<>();

    private List<String> methodBodyList = new ArrayList<>();

    public Set<String> getRequires() {
        return requires;
    }

    public String getEventId() {
        return eventId;
    }

    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    public String getRequestEntry() {
        return requestEntry.getNodeId();
    }

    public void setRequestEntry(NodeMetadata requestEntry) {
        this.requestEntry = requestEntry;
    }

    public void addScriptRequire(String require) {
        this.requires.add(require);
    }

    public List<String> getMethodBodyList() {
        return methodBodyList;
    }

    public void addMethod(String method) {
        this.methodBodyList.add(method);
    }

    public Buffer getBuffer() {
        return buffer;
    }

    /**
     * 解析树和当前对象
     *
     * @return
     */
    public String parse() {

        TreeNode<NodeTemplateParse> treeNode = convertTree.getTree(templateModelList, "nodeId", "parentNodeId");
        /**
         * 解析树，其中会生成一些额外的内容，用于当前对象解析
         */
        NodeTemplateParse root = treeNode.getData();
        root.parse(this, treeNode, buffer);

        /**
         * 解析当前对象
         */
        return ParserHolder.templateParser.parse(this);
    }
}
